import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client1 {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1",61234));

        new Thread(){
            @Override
            public void run() {
                while (true){
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    try {
                        int length = socketChannel.read(byteBuffer);
                        byteBuffer.flip();
                        String str = new String(byteBuffer.array(),0,length,"utf-8");
                        System.out.println(str);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();


    Scanner scanner = new Scanner(System.in);
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    while(true){
        System.out.println("请输入数据");
        String sendStr = scanner.nextLine();
        byteBuffer.put(sendStr.getBytes(StandardCharsets.UTF_8));
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
        byteBuffer.clear();
    }
    }
}
